package com.atguigu.aiproject.controller.admin;

import com.atguigu.aiproject.constant.PromptBuilder;
import com.atguigu.aiproject.entity.Result;
import com.atguigu.aiproject.service.AdminService;
import com.atguigu.aiproject.service.UserService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    private final UserService userService;
    private final AdminService adminService;
    private final ChatClient aiAdmin;

    public AdminController(UserService userService, ChatClient aiAdmin, AdminService adminService) {
        this.userService = userService;
        this.aiAdmin = aiAdmin;
        this.adminService = adminService;
    }

    @PostMapping(value = "/ai-management", produces = "text/event-stream;charset=utf-8")
    public Flux<String> aiManagement(@RequestBody Request request) {
        this.checkAdmin();
        return aiAdmin.prompt()
                .system(PromptBuilder.ADMIN_PROMPT)
                .user(request.request)
                .stream()
                .content();
    }



    //分页展示所有用户
    @GetMapping("/users")
    public Result<?> getUsers(@RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize) {
        this.checkAdmin();
        // 返回结果
        return Result.success(adminService.getUsers(pageNum, pageSize));
    }

    public static class Request {
        public String request;
    }

    // 删除用户接口
    @PostMapping("/delete")
    public Result<?> delete(@RequestParam Integer id) {
        this.checkAdmin();
        // 根据id删除用户，返回删除结果
        boolean removed = userService.deleteById(id);
        if (!removed) {
            return Result.error("用户不存在或删除失败");
        }
        return Result.success();
    }

    private void checkAdmin() {
        if (!adminService.isAdmin()) {
            throw new SecurityException("无管理员权限");
        }
    }
}